﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ARR.Shared;
using ARR.UI.Models;
using ARR.Entities;
using System.Collections.ObjectModel;
using System.Windows.Input;
using ARR.UI.Commands;
using DDF.Entity;
using System.Collections;
using Telerik.Windows.Controls.GridView;
using telerik = Telerik.Windows.Controls;
using Telerik.Windows.Controls;
using System.Windows.Data;
using ARR.UI.Views;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
using ARR.UI.RangeReviewsService;

namespace ARR.UI.ViewModels
{
    public class RangeReviewViewModel : WorkspaceViewModel
    {
        private IRangeReviewModel model;
        private RangeReview selectedRangeReview;
        private ICommand deleteCommand;
        private ICommand newCommand;
        private ICommand saveCommand;
        private ICommand cancelCommand;
        private ICommand updateExchangeRatesCommand;
        private ICommand benchmarksGV_RowValidatingCommand;
        private ICommand benchmarksGV_AddingNewDataItemCommand;
        private ICommand view_LoadedCommand;
        private ICommand setup_CheckAllCommand;
        private ICommand setup_UnCheckAllCommand;
        private ICommand newBenchmarkCommand;
        private ICommand deleteBenchmarkCommand;
        private ICommand editBenchmarkCommand;
        private History selectedHistory;



        public RangeReviewViewModel(IRangeReviewModel model)
        {
            this.DisplayName = Labels.RangeReviewManager;
            this.model = model;
            this.IsBusy = false;

            SelectedRangeReview = RangeReviews.Where(x => x.Id == WorkspaceData.Instance.RangeReview.Id).SingleOrDefault();
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.SelectedRangeReview);
        }


        public bool IsBusy { get; set; }

        public ICommand DeleteCommand
        {
            get
            {
                if (deleteCommand == null)
                {
                    deleteCommand = new RelayCommand(param => DeleteRangeReview(), param => SelectedRangeReview != null);
                }
                return deleteCommand;
            }
        }

        public ICommand NewCommand
        {
            get
            {
                if (newCommand == null)
                {
                    newCommand = new RelayCommand(param => CreateNewRangeReview());
                }
                return newCommand;
            }
        }

        public ICommand SaveCommand
        {
            get
            {
                if (saveCommand == null)
                {
                    saveCommand = new RelayCommand(param =>
                        {
                            string title = model.CurrentRangeReview != null ? model.CurrentRangeReview.Title : null;

                            SaveRangeReview();

                            SelectedRangeReview = RangeReviews.FirstOrDefault(x => x.Title == title);
                            OnPropertyChanged<RangeReviewViewModel>(vm => vm.SelectedRangeReview);


                        });
                }
                return saveCommand;
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                if (cancelCommand == null)
                {
                    cancelCommand = new RelayCommand(param => CancelEdition(), param => CanCancel());
                }
                return cancelCommand;
            }
        }

        public ICommand UpdateExchangeRatesCommand
        {
            get
            {
                if (updateExchangeRatesCommand == null)
                {
                    updateExchangeRatesCommand = new RelayCommand(param => UpdateExchangeRates());
                }
                return updateExchangeRatesCommand;
            }
        }

        public ICommand NewBenchmarkCommand
        {
            get
            {
                if (newBenchmarkCommand == null)
                {
                    newBenchmarkCommand = new RelayCommand(param => CreateNewBenchmark(), c => CurrentRangeReview != null);
                }
                return newBenchmarkCommand;
            }
        }

        public ICommand DeleteBenchmarkCommand
        {
            get
            {
                if (deleteBenchmarkCommand == null)
                {
                    deleteBenchmarkCommand = new RelayCommand(param => DeleteBenchmark(param as RangeReviewBenchmark));
                }
                return deleteBenchmarkCommand;
            }
        }

        public ICommand EditBenchmarkCommand
        {
            get
            {
                if (editBenchmarkCommand == null)
                {
                    editBenchmarkCommand = new RelayCommand(param => EditBenchmark(param as RangeReviewBenchmark));
                }
                return editBenchmarkCommand;
            }
        }

        public ICommand BenchmarksGV_RowValidatingCommand
        {
            get
            {
                if (benchmarksGV_RowValidatingCommand == null)
                {
                    benchmarksGV_RowValidatingCommand = new RelayCommand(e => OnBenchmarksGVRowValidating(e as telerik.GridViewRowValidatingEventArgs));
                }
                return benchmarksGV_RowValidatingCommand;
            }
        }

        public ICommand BenchmarksGV_AddingNewDataItemCommand
        {
            get
            {
                if (benchmarksGV_AddingNewDataItemCommand == null)
                {
                    benchmarksGV_AddingNewDataItemCommand = new RelayCommand(e => OnBenchmarksGVAddingNewDataItem(e as GridViewAddingNewEventArgs));
                }
                return benchmarksGV_AddingNewDataItemCommand;
            }
        }

        public ICommand View_LoadedCommand
        {
            get
            {
                if (view_LoadedCommand == null)
                {
                    view_LoadedCommand = new RelayCommand(param =>
                        {
                            var p = param as Telerik.Windows.Controls.GridViewColumnCollection;
                            if (p != null)
                            {
                                OnViewLoaded(p);
                            }
                            else
                            {
                                var p2 = param as DataTemplate;
                                if (p2 != null)
                                    OnViewLoaded(p2);
                            }
                        });
                }
                return view_LoadedCommand;
            }
        }

        public ICommand Setup_CheckAllCommand
        {
            get
            {
                if (setup_CheckAllCommand == null)
                {
                    setup_CheckAllCommand = new RelayCommand(param => OnSetupCheckAll(param as CheckBox));
                }
                return setup_CheckAllCommand;
            }
        }
        

        public ObservableCollection<RangeReview> RangeReviews
        {
            get
            {
                return model.RangeReviews;
            }
        }

        public List<RangeReviewSetup> RangeReviewSetups
        {
            get
            {
                return model.RRSetups;
            }
        }

        public RangeReview CurrentRangeReview
        {
            get
            {
                return model.CurrentRangeReview;
            }
        }

        public RangeReview SelectedRangeReview
        {
            get
            {
                return selectedRangeReview;
            }
            set
            {
                selectedRangeReview = value;

                if (selectedRangeReview != null && selectedRangeReview.Id != 0)
                {                    
                    if (DirtyCheck())
                    {
                        EntityState state = model.CurrentRangeReview.GetEntityState();
                        if (model.RRSetups != null)
                        {
                            model.CurrentRangeReview.RangeReviewSetups = model.RRSetups;

                            if (state == EntityState.Original && !model.RRSetups.Where(x => x.GetEntityState() != EntityState.Original).Any())
                                model.CurrentRangeReview.ChangeState(EntityState.Original);
                        }
                        model.Save();
                        model.CurrentRangeReview = null;
                        model.LoadCurrencies();
                        OnPropertyChanged<RangeReviewViewModel>(vm => vm.Currencies);
                        OnPropertyChanged<RangeReviewViewModel>(vm => vm.CurrencyExchangeRates);
                    }

                    IsBusy = true;
                    RangeReviewsServiceClient service = new RangeReviewsServiceClient();

                    try
                    {
                        service.GetByIdCompleted += new EventHandler<GetByIdCompletedEventArgs>(service_GetByIdCompleted);
                        service.GetByIdAsync(selectedRangeReview.Id, false);
                    }
                    catch (Exception ex)
                    {
                        IsBusy = false;
                        OnPropertyChanged<RangeReviewViewModel>(vm => vm.IsBusy);

                        service.Abort();
                        throw ex;
                    }

                }

                OnPropertyChanged<RangeReviewViewModel>(vm => vm.RangeReviews);
                OnPropertyChanged<RangeReviewViewModel>(vm => vm.CurrentRangeReview);
                OnPropertyChanged<RangeReviewViewModel>(vm => vm.RRStores);
                OnPropertyChanged<RangeReviewViewModel>(vm => vm.CurrencyExchangeRates);
                OnPropertyChanged<RangeReviewViewModel>(vm => vm.RangeReviewSetups);
                OnPropertyChanged<RangeReviewViewModel>(vm => vm.IsBusy);
            }
        }

        public ObservableCollection<Currency> Currencies
        {
            get
            {
                return model.Currencies;
            }
        }

        public ObservableCollection<RangeReviewStore> RRStores
        {
            get
            {
                return new ObservableCollection<RangeReviewStore>(model.RRStores.Where(x => x.Store.CountryId == selectedRangeReview.CountryId));
            }
        }

        public ObservableCollection<History> Histories
        {
            get 
            { 
                return new ObservableCollection<History>(model.Histories); 
            }
        }

        public History SelectedHistory 
        {
            get { return selectedHistory; }
            set
            {
                selectedHistory = value;

                if (selectedHistory != null)
                    CurrentRangeReview.PYHistoryId = selectedHistory.Id;
            }
        }

        public ObservableCollection<CurrencyExchangeRate> CurrencyExchangeRates
        {
            get
            {
                return model.CurrencyExchangeRates;
            }
        }

        public ObservableCollection<AttributeType> AttributeTypes
        {
            get
            {
                return model.AttributeTypes;
            }
        }

        public List<Store> SelectedStores { get; set; }

        public List<RangeReviewStore> SelectedRRStores { get; set; }

        public override List<string> ValidationErrors
        {
            get
            {
                return null;
            }
        }



        public void TriggerPropertyChanged()
        {
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.RRStores);
        }



        private bool DirtyCheck()
        {
            if (CurrentRangeReview != null)
            {
                if (CurrentRangeReview.GetEntityState() != EntityState.Original || (model.RRSetups != null && model.RRSetups.Where(x => x.GetEntityState() != EntityState.Original).Any()))
                {
                    Confirm dialog = new Confirm(string.Format("Hay cambios sin guardar en {0}, si no guarda estos cambios se perderan. ¿Desea guardar antes de seguir?", CurrentRangeReview.Title));

                    bool? dialogResult = dialog.ShowDialog();

                    if (dialogResult.HasValue && dialogResult.Value)
                    {
                        return true;//SaveRangeReview();
                    }
                }
            }

            return false;
        }

        private void DeleteRangeReview()
        {
            model.DeleteRangeReview(CurrentRangeReview);
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.RangeReviews);
        }

        private void CreateNewRangeReview()
        {
            DirtyCheck();

            model.CurrentRangeReview = new RangeReview()
            {
                Title = WorkspaceData.Instance.Country.Name + " xx",
                FirstMonth = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 01),
                TotalMonths = 6,
                CountryId = WorkspaceData.Instance.Country.Id,
                Country = WorkspaceData.Instance.Country,
                TargetCurrency = Currencies.SingleOrDefault(c => c.CurrencyISOCode == WorkspaceData.Instance.Country.CurrencyISOCode),
                TargetCurrencyId = Currencies.SingleOrDefault(c => c.CurrencyISOCode == WorkspaceData.Instance.Country.CurrencyISOCode).Id,
                RangeReviewStores = new List<RangeReviewStore>(),
                Benchmarks = new List<RangeReviewBenchmark>(),
                RangeReviewSetups = null
            };

            RangeReviews.Add(model.CurrentRangeReview);
            selectedRangeReview = model.CurrentRangeReview;
            model.RRSetups = null;

            OnPropertyChanged<RangeReviewViewModel>(vm => vm.SelectedRangeReview);
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.RangeReviews);
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.CurrentRangeReview);
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.RRStores);
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.CurrencyExchangeRates);
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.RangeReviewSetups);
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.IsBusy);
        }

        private void SaveRangeReview()
        {
            EntityState state = model.CurrentRangeReview.GetEntityState();
            if (model.RRSetups != null)
            {
                model.CurrentRangeReview.RangeReviewSetups = model.RRSetups;

                if (state == EntityState.Original && !model.RRSetups.Where(x => x.GetEntityState() != EntityState.Original).Any())
                    model.CurrentRangeReview.ChangeState(EntityState.Original);
            }

            model.Save();

            model.CurrentRangeReview = null;

            model.LoadCurrencies();
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.Currencies);
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.CurrencyExchangeRates);

            model.LoadRangeReviews();
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.RangeReviews);
        }

        private void CancelEdition()
        {
            model.LoadCurrencies();
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.Currencies);

            model.LoadRangeReviews();
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.RangeReviews);

            model.CurrentRangeReview = null;
            SelectedRangeReview = RangeReviews.FirstOrDefault();

            OnPropertyChanged<RangeReviewViewModel>(vm => vm.CurrencyExchangeRates);
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.RRStores);
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.CurrentRangeReview);
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.SelectedRangeReview);

        }

        private bool CanSave()
        {
            return CurrentRangeReview != null && CurrentRangeReview.GetEntityState() != EntityState.Original;
        }

        private bool CanCancel()
        {
            return CurrentRangeReview != null && CurrentRangeReview.GetEntityState() != EntityState.Original;
        }

        private void GetCurrencyExchangeRates()
        {
            //Syncs the two collections.
            foreach (var rate in CurrencyExchangeRates)
            {
                if (!model.CountryCurrencyExchangeRates.Any(r => r.Date == rate.Date && r.TargetCurrencyId == rate.TargetCurrencyId))
                {
                    model.CountryCurrencyExchangeRates.Add(rate);
                }
            }

            if(CurrencyExchangeRates != null && CurrencyExchangeRates.Any())
                CurrencyExchangeRates.Clear();

            int months = CurrentRangeReview.TotalMonths;
            if (CurrentRangeReview.HasPriorYear)
            {
                months = CurrentRangeReview.TotalMonths * 2;
            }
                        
            for (int i = 0; i <= CurrentRangeReview.TotalMonths - 1; i++)
            {
                DateTime monthCY = CurrentRangeReview.FirstMonth.AddMonths(i);
                DateTime monthPY = monthCY.AddYears(-1);

                int countryCurrencyId = Currencies.Single(x => x.CountryId == WorkspaceData.Instance.Country.Id).Id;

                var rateCY = model.CountryCurrencyExchangeRates.SingleOrDefault(p => p.Date.Month == monthCY.Month && p.Date.Year == monthCY.Year && p.SourceCurrencyId == countryCurrencyId && p.TargetCurrencyId == CurrentRangeReview.TargetCurrencyId);
                var ratePY = model.CountryCurrencyExchangeRates.SingleOrDefault(p => p.Date.Month == monthPY.Month && p.Date.Year == monthPY.Year && p.SourceCurrencyId == countryCurrencyId && p.TargetCurrencyId == CurrentRangeReview.TargetCurrencyId);

                Currency targetCurrency = Currencies.SingleOrDefault(x => x.Id == CurrentRangeReview.TargetCurrencyId);
                Currency sourceCurrency = Currencies.SingleOrDefault(x => x.Id == countryCurrencyId);
                if (sourceCurrency == null)
                {
                    sourceCurrency = Currencies.FirstOrDefault(x => x.CurrencyISOCode == "USD");
                }
                if (targetCurrency == null)
                {
                    targetCurrency = Currencies.FirstOrDefault(x => x.CurrencyISOCode == "USD");
                }

                if (rateCY == null)
                {
                    rateCY = new CurrencyExchangeRate
                    {
                        CountryId = WorkspaceData.Instance.Country.Id,
                        SourceCurrencyId = sourceCurrency.Id,
                        TargetCurrency = targetCurrency,
                        TargetCurrencyId = targetCurrency.Id,
                        Date = monthCY,
                        Rate = 0,
                        ForexRate = 0
                    };
                }

                if (ratePY == null)
                {
                    ratePY = new CurrencyExchangeRate
                    {
                        CountryId = WorkspaceData.Instance.Country.Id,
                        SourceCurrencyId = sourceCurrency.Id,
                        TargetCurrency = targetCurrency,
                        TargetCurrencyId = targetCurrency.Id,
                        Date = monthPY,
                        Rate = 0,
                        ForexRate = 0
                    };
                }

                if (sourceCurrency.Id == targetCurrency.Id)
                {
                    rateCY.Rate = 1;
                    rateCY.ForexRate = 1;
                    ratePY.Rate = 1;
                    ratePY.ForexRate = 1;
                }

                CurrencyExchangeRates.Add(rateCY);
                CurrencyExchangeRates.Add(ratePY);
            }
        }

        public void GetRangeReviewSetups(int rangeReviewId)
        {
            if (this.RangeReviewSetups == null)
            {
                model.GetRangeReviewSetups(rangeReviewId);
                OnPropertyChanged<RangeReviewViewModel>(p => p.RangeReviewSetups);
            }
        }

        private void UpdateExchangeRates()
        {
            try
            {
                if (CurrentRangeReview != null)
                {
                    GetCurrencyExchangeRates();
                    OnPropertyChanged<RangeReviewViewModel>(p => p.CurrencyExchangeRates);
                }
            }
            catch(Exception ex)
            {
                string msg = ex.Message;
            }
        }

        private void OnBenchmarksGVAddingNewDataItem(GridViewAddingNewEventArgs e)
        {
            e.NewObject = new RangeReviewBenchmark { RangeReviewSourceId = CurrentRangeReview.Id };
        }

        private void OnBenchmarksGVRowValidating(telerik.GridViewRowValidatingEventArgs e)
        {
            if (e.EditOperationType == GridViewEditOperationType.Insert)
            {
                RangeReviewBenchmark newBenchmark = e.Row.DataContext as RangeReviewBenchmark;

                if (!newBenchmark.IsValid)
                {
                    e.IsValid = false;
                }
            }
        }

        private void OnViewLoaded(telerik.GridViewColumnCollection columns)
        {
            if (AttributeTypes != null)
            {
                int indexer = 0;
                foreach (AttributeType type in AttributeTypes.OrderBy(x => x.Id))
                {
                    GridViewCheckBoxColumn col = new GridViewCheckBoxColumn();
                    //col.Header = type.Name;
                    col.UniqueName = type.Name;
                    col.AutoSelectOnEdit = true;
                    col.DataMemberBinding = new Binding(string.Format("Attributes[{0}].IsChecked", indexer++));


                    StackPanel sp = new StackPanel { Orientation = Orientation.Horizontal };

                    TextBlock txt = new TextBlock();
                    txt.Text = type.Name + " ";
                    sp.Children.Add(txt);


                    CheckBox chk = new CheckBox() { Tag = type.Name };
                    chk.Uid = type.Name;
                    System.Windows.Interactivity.EventTrigger triggerChecked = new System.Windows.Interactivity.EventTrigger("Checked");
                    Helpers.EventToCommand eventToCommand = new Helpers.EventToCommand();
                    eventToCommand.Command = Setup_CheckAllCommand;                    
                    eventToCommand.CommandParameter = chk;//type.Name;
                    triggerChecked.Actions.Add(eventToCommand);
                    triggerChecked.Attach(chk);

                    System.Windows.Interactivity.EventTrigger triggerUnchecked = new System.Windows.Interactivity.EventTrigger("Unchecked");
                    Helpers.EventToCommand uncheched = new Helpers.EventToCommand();
                    uncheched.Command = Setup_CheckAllCommand; //Setup_UnCheckAllCommand;
                    uncheched.CommandParameter = chk;//type.Name;
                    triggerUnchecked.Actions.Add(uncheched);
                    triggerUnchecked.Attach(chk);

                    sp.Children.Add(chk);

                    col.Header = sp;

                    columns.Add(col);
                }
            }
        }

        private void OnViewLoaded(DataTemplate rowDetailTemplate)
        {
            RadGridView gv = rowDetailTemplate.LoadContent() as RadGridView;
            if (gv != null)
            {
                if (AttributeTypes != null)
                {
                    int indexer = 0;
                    foreach (AttributeType type in AttributeTypes.OrderBy(x => x.Id))
                    {
                        GridViewCheckBoxColumn col = new GridViewCheckBoxColumn();
                        col.Header = type.Name;
                        col.UniqueName = type.Name;
                        col.AutoSelectOnEdit = true;
                        col.DataMemberBinding = new Binding(string.Format("Attributes[{0}].IsChecked", indexer++));

                        gv.Columns.Add(col);
                    }
                }
            }
        }

        private void OnSetupCheckAll(CheckBox check)
        {
            if (RangeReviewSetups != null)
            {
                foreach (var setup in RangeReviewSetups)
                {
                    switch (check.Tag.ToString())
                    {
                        case "Sales":
                            {
                                setup.Sales = check.IsChecked.Value;
                                //if (setup.SubCategoriesSetups != null)
                                //    setup.SubCategoriesSetups.ForEach(x => x.Sales = true);
                                break;
                            }
                        case "Skus":
                            {
                                setup.SKUs = check.IsChecked.Value;
                                //if (setup.SubCategoriesSetups != null)
                                //    setup.SubCategoriesSetups.ForEach(x => x.SKUs = true);
                                break;
                            }
                        case "Units":
                            {
                                setup.Units = check.IsChecked.Value;
                                //if (setup.SubCategoriesSetups != null)
                                //    setup.SubCategoriesSetups.ForEach(x => x.Units = true);
                                break;
                            }
                        case "Margin":
                            {
                                setup.Margin = check.IsChecked.Value;
                                //if (setup.SubCategoriesSetups != null)
                                //    setup.SubCategoriesSetups.ForEach(x => x.Margin = true);
                                break;
                            }
                        case "Inventory":
                            {
                                setup.Inventory = check.IsChecked.Value;
                                //if (setup.SubCategoriesSetups != null)
                                //    setup.SubCategoriesSetups.ForEach(x => x.Inventory = true);
                                break;
                            }
                        case "Space":
                            {
                                setup.Space = check.IsChecked.Value;
                                //if (setup.SubCategoriesSetups != null)
                                //    setup.SubCategoriesSetups.ForEach(x => x.Space = true);
                                break;
                            }
                        case "Subcategory":
                            {
                                setup.Subcategory = check.IsChecked.Value;
                                //if (setup.SubCategoriesSetups != null)
                                //    setup.SubCategoriesSetups.ForEach(x => x.Subcategory = true);
                                break;
                            }
                        case "Brand":
                            {
                                setup.Brand = check.IsChecked.Value;
                                //if (setup.SubCategoriesSetups != null)
                                //    setup.SubCategoriesSetups.ForEach(x => x.Brand = true);
                                break;
                            }
                        case "Manufacturer":
                            {
                                setup.Manufacturer = check.IsChecked.Value;
                                //if (setup.SubCategoriesSetups != null)
                                //    setup.SubCategoriesSetups.ForEach(x => x.Manufacturer = true);
                                break;
                            }
                        case "Attribute1":
                            {
                                setup.Attribute1 = check.IsChecked.Value;
                                //if (setup.SubCategoriesSetups != null)
                                //    setup.SubCategoriesSetups.ForEach(x => x.Attribute1 = true);
                                break;
                            }
                        case "Attribute2":
                            {
                                setup.Attribute2 = check.IsChecked.Value;
                                //if (setup.SubCategoriesSetups != null)
                                //    setup.SubCategoriesSetups.ForEach(x => x.Attribute2 = true);
                                break;
                            }
                        case "Attribute3":
                            {
                                setup.Attribute3 = check.IsChecked.Value;
                                //if (setup.SubCategoriesSetups != null)
                                //    setup.SubCategoriesSetups.ForEach(x => x.Attribute3 = true);
                                break;
                            }
                        case "Attribute4":
                            {
                                setup.Attribute4 = check.IsChecked.Value;
                                //if (setup.SubCategoriesSetups != null)
                                //    setup.SubCategoriesSetups.ForEach(x => x.Attribute4 = true);
                                break;
                            }
                        case "Attribute5":
                            {
                                setup.Attribute5 = check.IsChecked.Value; 
                                //if (setup.SubCategoriesSetups != null)
                                //    setup.SubCategoriesSetups.ForEach(x => x.Attribute5 = true);
                                break;
                            }
                        case "LinearMeters":
                            {
                                setup.LinearMeters = check.IsChecked.Value;
                                //if (setup.SubCategoriesSetups != null)
                                //    setup.SubCategoriesSetups.ForEach(x => x.Attribute5 = true);
                                break;
                            }
                        case "SquareMeters":
                            {
                                setup.SquareMeters = check.IsChecked.Value;
                                //if (setup.SubCategoriesSetups != null)
                                //    setup.SubCategoriesSetups.ForEach(x => x.Attribute5 = true);
                                break;
                            }
                        case "Benchmarks":
                            {
                                setup.Benchmarks = check.IsChecked.Value;
                                break;
                            }
                        default:
                            {
                                AttributeType att = AttributeTypes.SingleOrDefault(x => x.Name == check.Tag.ToString());
                                if (att != null)
                                {
                                    setup.Attributes.Single(x => x.AttributeTypeId == att.Id).IsChecked = check.IsChecked.Value;

                                    //if (setup.SubCategoriesSetups != null)
                                    //    setup.SubCategoriesSetups.ForEach(x =>
                                    //        {
                                    //            x.Attributes.Single(y => y.AttributeTypeId == att.Id).IsChecked = true;
                                    //        });
                                }
                                break;
                            }
                    }
                }
            }

            model.RRSetups = new List<RangeReviewSetup>(this.RangeReviewSetups);
            OnPropertyChanged<RangeReviewViewModel>(p => p.RangeReviewSetups);
        }

        private void CreateNewBenchmark()
        {
            if (CurrentRangeReview != null)
            {
                if (CurrentRangeReview.Benchmarks == null)
                {
                    CurrentRangeReview.Benchmarks = new List<RangeReviewBenchmark>();
                }

                BenchmarkEditViewModel vm = new BenchmarkEditViewModel(this.model, CurrentRangeReview, null);

                BenchmarkEditView benchmarkView = new BenchmarkEditView { DataContext = vm };

                benchmarkView.ShowDialog();

                CurrentRangeReview.Benchmarks = new List<RangeReviewBenchmark>(CurrentRangeReview.Benchmarks);
                OnPropertyChanged<RangeReviewViewModel>(p => p.CurrentRangeReview.Benchmarks);
            }
        }

        private void DeleteBenchmark(RangeReviewBenchmark rangeReviewBenchmark)
        {
            RangeReviews.ToList().ForEach(rr =>
            {
                if (rr.Benchmarks.Contains(rangeReviewBenchmark))
                {
                    rr.Benchmarks.Remove(rangeReviewBenchmark);
                    return;
                }
            });


            CurrentRangeReview.Benchmarks = new List<RangeReviewBenchmark>(CurrentRangeReview.Benchmarks);
            OnPropertyChanged<RangeReviewViewModel>(p => p.CurrentRangeReview.Benchmarks);
        }

        private void EditBenchmark(RangeReviewBenchmark rangeReviewBenchmark)
        {
            BenchmarkEditViewModel vm = new BenchmarkEditViewModel(this.model, CurrentRangeReview, rangeReviewBenchmark);

            BenchmarkEditView benchmarkView = new BenchmarkEditView { DataContext = vm };

            bool? res = benchmarkView.ShowDialog();

            if (!res.HasValue || (res.HasValue && res == false))
            {
                CancelEdition();
            }
            else
            {
                CurrentRangeReview.Benchmarks = new List<RangeReviewBenchmark>(CurrentRangeReview.Benchmarks);
                OnPropertyChanged<RangeReviewViewModel>(p => p.CurrentRangeReview.Benchmarks);
            }
        }

        void service_GetByIdCompleted(object sender, GetByIdCompletedEventArgs e)
        {
            IsBusy = false;

            model.CurrentRangeReview = e.Result;

            GetCurrencyExchangeRates();

            model.RRSetups = model.CurrentRangeReview.RangeReviewSetups;
            model.CurrentRangeReview.RangeReviewSetups = null;
            
            model.CurrentRangeReview.ChangeState(EntityState.Original);

            if (model.CurrentRangeReview.PYHistoryId.HasValue)
            {
                SelectedHistory = Histories.SingleOrDefault(x => x.Id == model.CurrentRangeReview.PYHistoryId.Value);
            }


            OnPropertyChanged<RangeReviewViewModel>(vm => vm.SelectedHistory);
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.RangeReviews);
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.CurrentRangeReview);
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.RRStores);
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.CurrencyExchangeRates);
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.RangeReviewSetups);
            OnPropertyChanged<RangeReviewViewModel>(vm => vm.IsBusy);
        }
    }
}
